package com.xxxx;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.util.Arrays;

public class Hello04FlinkOperatorFlatMap {

    public static void main(String[] args) throws Exception {
        //获取执行环境
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();
        //获取数据源
        DataSource<String> source = environment.fromElements("aa bb cc", "aa bb", "aa");
        //开始进行转换
        //source.flatMap(new FlatMapFunction<String, String>() {
        //    @Override
        //    public void flatMap(String s, Collector<String> collector) throws Exception {
        //        Arrays.stream(s.split(" ")).forEach(word -> collector.collect(word));
        //    }
        //}).map(new MapFunction<String, Tuple2<String, Integer>>() {
        //    @Override
        //    public Tuple2<String, Integer> map(String s) throws Exception {
        //        return Tuple2.of(s, 1);
        //    }
        //}).print();

        // Lambda 一定要主要添加返回类型
        //source.flatMap((String line, Collector<String> collector) -> {
        //    Arrays.stream(line.split(" ")).forEach(word -> collector.collect(word));
        //}).returns(Types.STRING).map(word -> {
        //    return Tuple2.of(word, 1);
        //}).returns(Types.TUPLE(Types.STRING, Types.INT)).print();

        //取巧的办法 绕过Map
        source.flatMap((String line, Collector<Tuple2<String, Integer>> collector) -> {
            Arrays.stream(line.split(" ")).forEach(word -> collector.collect(Tuple2.of(word, 1)));
        }).returns(Types.TUPLE(Types.STRING, Types.INT)).print();

    }

}
